package com.agileai.miscdp.hotweb.ui.actions.treemanage;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.progress.IProgressService;

import com.agileai.miscdp.DeveloperConst;
import com.agileai.miscdp.hotweb.database.DBManager;
import com.agileai.miscdp.hotweb.domain.Column;
import com.agileai.miscdp.hotweb.domain.ProjectConfig;
import com.agileai.miscdp.hotweb.domain.treemanage.TreeManageFuncModel;
import com.agileai.miscdp.hotweb.ui.actions.BaseInitGridAction;
import com.agileai.miscdp.hotweb.ui.editors.treemanage.TMMBasicConfigPage;
import com.agileai.miscdp.hotweb.ui.editors.treemanage.TreeManageModelEditor;
import com.agileai.miscdp.hotweb.ui.editors.treemanage.TreeManageModelEditorContributor;
import com.agileai.miscdp.util.DialogUtil;
import com.agileai.miscdp.util.MiscdpUtil;
import com.agileai.util.StringUtil;
/**
 * 初始化表中功能模型数据
 */
public class TMMInitGridAction extends BaseInitGridAction{
	private TMMBasicConfigPage basicConfigPage;
	
	private String tableName;
	public TMMInitGridAction() {
	}
	public void setContributor(TreeManageModelEditorContributor contributor) {
		this.contributor = contributor;
	}
	private String getPkGenPolicy(String tableName){
		String result = "";
		IWorkbenchPage workbenchPage = contributor.getPage();
		IEditorPart editorPart = workbenchPage.getActiveEditor();
		modelEditor = (TreeManageModelEditor)editorPart;
		String projectName = modelEditor.getFuncModel().getProjectName();
		Column[] columns = DBManager.getInstance(projectName).getColumns(tableName);
		if (columns != null && columns.length > 0){
			int count = columns.length;
			for (int i=0;i < count;i++){
				Column column = columns[i];
				if (column.isPK()){
					if ("java.lang.Integer".equals(column.getClassName())
							|| "java.lang.Long".equals(column.getClassName())){
						result = Column.PKType.INCREASE;
						break;
					}
					else if ("java.lang.String".equals(column.getClassName())){
						if (column.getLength() == 36){
							result = Column.PKType.CHARGEN;
							break;
						}
						else{
							result = Column.PKType.ASSIGN;
							break;
						}
					}
				}
			}
		}
		return result;
	}
	public void run() {
		IWorkbenchPage workbenchPage = contributor.getPage();
		IEditorPart editorPart = workbenchPage.getActiveEditor();
		modelEditor = (TreeManageModelEditor)editorPart;
		this.basicConfigPage = ((TreeManageModelEditor)modelEditor).getBasicConfigPage();
		String funcSubPkg = basicConfigPage.getFuncSubPkgText().getText();
		if (StringUtils.isBlank(funcSubPkg)){
			DialogUtil.showInfoMessage("编码目录不能为空！");
			return;
		}
		String sortField = basicConfigPage.getSortFieldText().getText();
		String nameField = basicConfigPage.getNameFieldText().getText();
		String pidField = basicConfigPage.getPidFieldText().getText();
		String idField = basicConfigPage.getIdFieldText().getText();
		if (StringUtils.isBlank(idField)){
			DialogUtil.showInfoMessage("节点ID字段不能为空！");
			return;
		}
		if (StringUtils.isBlank(pidField)){
			DialogUtil.showInfoMessage("父节点ID字段不能为空！");
			return;
		}
		if (StringUtils.isBlank(nameField)){
			DialogUtil.showInfoMessage("节点名称字段不能为空！");
			return;
		}		
		if (StringUtils.isBlank(sortField)){
			DialogUtil.showInfoMessage("节点排序字段不能为空！");
			return;
		}		
		
		Combo tableNameCombo = basicConfigPage.getTableNameCombo();
		tableName = tableNameCombo.getText();
		Shell shell = modelEditor.getSite().getShell();
		if (StringUtil.isNullOrEmpty(tableName)){
			DialogUtil.showMessage(shell,"消息提示","请先选择数据表!",DialogUtil.MESSAGE_TYPE.WARN);
			return;
		}
		
		String projectName = modelEditor.getFuncModel().getProjectName();
		String[] primaryKeys = DBManager.getInstance(projectName).getPrimaryKeys(tableName);
		if (primaryKeys == null){
			MessageDialog.openInformation(shell, "消息提示","所选择的数据表没有主键!");
			return;
		}
		boolean doInitGrid = MessageDialog.openConfirm(shell,"消息提示","自动填写可能会覆盖已有内容，是否继续!");
		if (!doInitGrid){
			return;
		}
		
        IProgressService progressService = PlatformUI.getWorkbench().getProgressService();
        IRunnableWithProgress runnable = new IRunnableWithProgress() {
			public void run(IProgressMonitor monitor) throws InvocationTargetException {
				try {
					doRun(monitor);
				} catch (Exception e) {
					throw new InvocationTargetException(e);
				} finally {
					monitor.done();
				}
			}
        };
        try {
			progressService.runInUI(PlatformUI.getWorkbench().getProgressService(),
					runnable,ResourcesPlugin.getWorkspace().getRoot());
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	public void doRun(IProgressMonitor monitor) {
		monitor.beginTask("init grid values....", 1000);
		monitor.subTask("init basic values....");
		monitor.worked(50);
		((TreeManageModelEditor)modelEditor).buildFuncModel();
		TreeManageFuncModel funcModel = ((TreeManageModelEditor)modelEditor).getFuncModel();
		try {
			funcModel.setTableName(tableName);
			
			String funcSubPkg = basicConfigPage.getFuncSubPkgText().getText();
			funcModel.setFuncSubPkg(funcSubPkg);
			String pkGenPolicy = getPkGenPolicy(tableName);
			funcModel.setPkGenPolicy(pkGenPolicy);
			String namePrefix = MiscdpUtil.getValidName(tableName);
			String beanIdPrefix = namePrefix.substring(0,1).toLowerCase()+namePrefix.substring(1,namePrefix.length());
			
			funcModel.setJspName(funcSubPkg +"/"+namePrefix+"TreeManage.jsp");
			String funcName = funcModel.getFuncName();
			funcModel.setPageTitle(funcName);
			funcModel.setServiceId(beanIdPrefix+"TreeManageService");
			
			String projectName = funcModel.getProjectName();
			ProjectConfig projectConfig = new ProjectConfig();
			String configFile = MiscdpUtil.getCfgFileName(projectName,DeveloperConst.PROJECT_CFG_NAME);
			projectConfig.setConfigFile(configFile);
			projectConfig.initConfig();
			String mainPkg = projectConfig.getMainPkg();
			funcModel.setImplClassName(mainPkg +".bizmoduler."+funcSubPkg+"."+namePrefix +"TreeManageImpl");
			funcModel.setInterfaceName(mainPkg +".bizmoduler."+funcSubPkg+"."+namePrefix+"TreeManage");
			
			DBManager dbManager = DBManager.getInstance(projectName);
			Column[] columns = dbManager.getColumns(tableName);
			List<Column> filterdColumnList = new ArrayList<Column>();
			for (int i=0;i < columns.length;i++){
				Column column = columns[i];
				String columnName = column.getName();
				if (columnName.equals(funcModel.getSortField())
						|| columnName.equals(funcModel.getParentIdField())){
					continue;
				}
				filterdColumnList.add(column);
			}
			columns = filterdColumnList.toArray(new Column[0]);
			TreeManageFuncModel.initPageFormFields(columns, funcModel.getPageFormFields(),null);
		} catch (Exception e) {
			e.printStackTrace();
		}
		((TreeManageModelEditor)modelEditor).setFuncModel(funcModel);
		modelEditor.initValues();
		
		monitor.subTask("refresh viewer....");
		monitor.worked(900);
		
		TableViewer tableViewer = ((TreeManageModelEditor)modelEditor).getJspCfgPage().getTableViewer();
		tableViewer.setInput(funcModel.getPageFormFields());
		tableViewer.refresh();
		return;
	}
}
